#include "bsp_can.h"

/**
************************************************************************
* @brief:      	can_filter_init(void)
* @param:       void
* @retval:     	void
* @details:    	CAN滤波器初始化
************************************************************************
**/
void BSP_CAN_Init(void)
{
    FDCAN_FilterTypeDef fdcan_filter;

    fdcan_filter.IdType = FDCAN_STANDARD_ID;              // 标准ID
    fdcan_filter.FilterIndex = 0;                         // 滤波器索引
    fdcan_filter.FilterType = FDCAN_FILTER_RANGE;         // 滤波器类型
    fdcan_filter.FilterConfig = FDCAN_FILTER_TO_RXFIFO0;  // 过滤器0关联到FIFO0
    fdcan_filter.FilterID1 = 0x0000;                      // 32位ID
    fdcan_filter.FilterID2 = 0x0000;  // 如果FDCAN配置为传统模式的话，这里是32位掩码
    if(HAL_FDCAN_ConfigFilter(&hfdcan1, &fdcan_filter) != HAL_OK)  // 滤波器初始化
    {
        Error_Handler();
    }
    HAL_FDCAN_Start(&hfdcan1);  // 开启FDCAN
    HAL_FDCAN_ActivateNotification(&hfdcan1, FDCAN_IT_RX_FIFO0_NEW_MESSAGE, 0);
}

/**
************************************************************************
* @brief:      	fdcanx_bsp_send_data(FDCAN_HandleTypeDef *hfdcan, uint16_t id, uint8_t *data, uint32_t len)
* @param:       hfdcan；FDCAN句柄
* @param:       id：CAN设备ID
* @param:       data：发送的数据
* @param:       len：发送的数据长度
* @retval:     	void
* @details:    	发送数据
************************************************************************
**/
uint8_t fdcanx_bsp_send_data(FDCAN_HandleTypeDef* hfdcan, uint16_t id, uint8_t* data, uint32_t len)
{
    FDCAN_TxHeaderTypeDef TxHeader;

    TxHeader.Identifier = id;
    TxHeader.IdType = FDCAN_STANDARD_ID;
    TxHeader.TxFrameType = FDCAN_DATA_FRAME;
    TxHeader.DataLength = len;
    TxHeader.ErrorStateIndicator = FDCAN_ESI_ACTIVE;
    TxHeader.BitRateSwitch = FDCAN_BRS_OFF;
    TxHeader.FDFormat = FDCAN_CLASSIC_CAN;
    TxHeader.TxEventFifoControl = FDCAN_NO_TX_EVENTS;
    TxHeader.MessageMarker = 0x52;

    if(HAL_FDCAN_AddMessageToTxFifoQ(hfdcan, &TxHeader, data) != HAL_OK)
        return 1;  // 发送
    return 0;
}

__weak void USER_CAN1fifo0Callback(uint32_t Identifier, uint8_t* Data) {}

void HAL_FDCAN_RxFifo0Callback(FDCAN_HandleTypeDef* hfdcan, uint32_t RxFifo0ITs)
{
    if((RxFifo0ITs & FDCAN_IT_RX_FIFO0_NEW_MESSAGE) != RESET)
    {
        FDCAN_RxHeaderTypeDef RxHeader;
        uint8_t Data[8];
        HAL_FDCAN_GetRxMessage(hfdcan, FDCAN_RX_FIFO0, &RxHeader, Data);
        if(hfdcan == &hfdcan1)
        {
            USER_CAN1fifo0Callback(RxHeader.Identifier, Data);
        }
    }
}
